package com.aishua.fire.common;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;

import org.springframework.web.multipart.MultipartFile;

public class FileUtil {
		
	//链接url下载图片
	public static void downloadPicture(String urlList,File file) {
        try {
        	InputStream fot = new FileInputStream(urlList);
            DataInputStream dataInputStream = new DataInputStream(fot);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length;
 
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 判断文件是否存在
    public static Boolean judeFileExists(String fileUrl,MultipartFile newFile) {
    	File file = new File(fileUrl);
    	if (file.exists()) {
    		file.delete();
    		uploadImage(newFile,fileUrl);
    		return true;
    	} else {
    		return false;
    	}
    }
    
    
    
 // 判断文件是否存在
    public static Boolean fileExists(File file) {
    	if (file.exists()) {
    		return true;
    	} else {
    		return false;
    	}
    }
    
    public static void deleteFile(String fileUrl) {
    	File file = new File(fileUrl);
    	if (file.exists()) {
    	} else {
    		file.delete();
    	}
    }
    public static void uploadImage(MultipartFile file,String filePath) {
	    if (!file.isEmpty()) {
	        // 转存文件
	        try {
	        	
				file.transferTo(new File(filePath));
			} catch (Exception e) {
				throw new RuntimeException("文件上传失败");
			}
	    }
    }
    
}
